//
//  Kratos_PayView_kra.m
//  kk_framework
//
//  Created by 7yao.top on 2018/11/27.
//  Copyright © 2018年 7yao.top. All rights reserved.
//

#import "NNN_CallView_nnn.h"
#import "Kratos_Tool.h"
#import <AdSupport/AdSupport.h>
#import "Kratos_userInfo.h"
#import <JavaScriptCore/JavaScriptCore.h>
#import "Kratos_Options.h"
#import "Kratos_HttpConfigure.h"
#import <WebKit/WebKit.h>
#import "YYY_ModelMethod_yyy.h"
#import "Masonry.h"
#import "k_const.h"
#import "YYModel.h"

@interface NNN_CallView_nnn()<WKNavigationDelegate,WKUIDelegate,UIScrollViewDelegate,ModelCallPageViewDelegate>

@property (strong, nonatomic)   WKWebView *webView;


@end

@implementation NNN_CallView_nnn


- (instancetype)init
{
    self = [super init];
    if (self) {
        
//        self.layer.cornerRadius = 5;
//        self.clipsToBounds = YES;
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}


-(void)NNN_ModelCloseCallPageView_nnn{
    
//    [self.delegate NNN_CloseCallPageView_nnn];
}


- (void)loadWebViewWithUid:(NSString *)uid
                    AndFee:(NSString *)fee
                  AndGoods:(NSString *)goods
                    AndSid:(NSString *)sid
                 AndAttach:(NSString *)attach{
    

    
    NSDictionary *dic = @{@"uid":uid,
                          @"fee":fee,
                          @"goods":goods,
                          @"sid":sid,
                          @"attach":attach};


    NSString *pre = @"/:sptth";
    NSString *str = [@"yalp/emag/xedni/pot.emagzl.emag/" stringByAppendingString:pre];


    Kratos_userInfo *userInfo  = [Kratos_userInfo Kratos_getCurrentUserInfo_Kratos];
    Kratos_Options *option = [Kratos_HttpConfigure sharedHttpConfigure].Kra_option;
    NSString *GameID = option.Kratos_GameID;
    NSString *exmodel =  [Kratos_Tool Kratos_getDeviceName_Kratos];
    NSString * IDFA =  [ASIdentifierManager sharedManager].advertisingIdentifier.UUIDString;
    NSString *Pkg = option.Kratos_pkg;

    NSString *SDKVersion = option.Kratos_sdkver;
    NSString *AppVersion =  [NSBundle mainBundle].infoDictionary[@"CFBundleShortVersionString"];
    NSString *dicStr = [[Kratos_Tool Kratos_dictionaryToJson_ccc:dic]stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    NSString *uidN = userInfo.Kra_ID;
    NSString *token = userInfo.Kra_token;
    NSString *CID = option.Kratos_CID;
    NSString *ChidID = option.Kratos_chidID;
    
    NSString *url = [NSString stringWithFormat:@"%@?inm=1&gameid=%@&exmodel=%@&idfa=%@&pkg=%@&sdkver=%@&version=%@&payparam=%@&uid=%@&token=%@&cid=%@&chid=%@",[Kratos_Tool Kratos_inputValue:str],GameID,exmodel,IDFA,Pkg,SDKVersion,AppVersion,dicStr,uidN,token,CID,ChidID];
    [self WebViewWithURL:url];
    
    
    

    
}
- (void)deleteWebCache {
    // 清除所有
    

    NSString *libraryDir = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,NSUserDomainMask, YES)[0];
    NSString *bundleId = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleIdentifier"];
    NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
    NSString *webKitFolderInCaches = [NSString stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
    NSError *error;
    [[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
    [[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
    
 
    
    NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
    NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];

    //// Execute

    [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{

        // Done
        NSLog(@"清楚缓存完毕");

    }];


    
 
}


- (void)WebViewWithURL:(NSString *)url{
    
    [self deleteWebCache];


    WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
    
    self.webView = [[WKWebView alloc] initWithFrame:self.frame configuration:configuration];
    self.webView.navigationDelegate = self;
    self.webView.UIDelegate = self;
    self.webView.scrollView.bounces = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.scrollView.scrollEnabled = NO;
    [self addSubview:self.webView];
    
    

    
    
    
    NSCharacterSet *encodeUrlSet = [NSCharacterSet URLQueryAllowedCharacterSet];
    url = [url stringByAddingPercentEncodingWithAllowedCharacters:encodeUrlSet];
    

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
    
    
    UIWebView *webView = [[UIWebView alloc] initWithFrame:CGRectZero];
    NSString *oldAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
    
    // 给User-Agent添加额外的信息
    NSString *newAgent = [NSString stringWithFormat:@"%@", oldAgent];
    
    // 设置global User-Agent
    NSDictionary *dictionnary = [[NSDictionary alloc] initWithObjectsAndKeys:newAgent, @"UserAgent", nil];
    [[NSUserDefaults standardUserDefaults] registerDefaults:dictionnary];
    
    
    //    // 修改UA的格式 方便H5端判定前后版本差别
    [self.webView evaluateJavaScript:@"navigator.userAgent" completionHandler:^(id result, NSError *error) {

        NSString * agentStr = [NSString stringWithFormat:@"%@ Platform/ios Browser/%@",result,@"WKWebView"];
        [[NSUserDefaults standardUserDefaults] registerDefaults:@{@"UserAgent":agentStr}];
        [[NSUserDefaults standardUserDefaults] synchronize];
        if (@available(iOS 9.0, *)) {
            [self.webView setCustomUserAgent:agentStr];
        } else {
//            [self.webView setCustomUserAgent:agentStr];
        }
    }];
    
    
    [self.webView loadRequest:request];
    
    
    
}


#pragma mark 网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    
    NSString *persent = nil;
    CGFloat QYScreenW = [UIScreen mainScreen].bounds.size.width;
    
    if (QYScreenW == 480) {           //4/4s
        persent = @"60";
    }else if (QYScreenW == 568){      //5/5s/5c
        persent = @"60";
    }else if (QYScreenW == 667){      //6/6s/7/8
        persent = @"85";
    }else if (QYScreenW == 736){      //6+/6s+/7+/8+
        persent = @"95";
    }else if (QYScreenW == 812){      //X
        persent = @"95";
    }else{
        persent = @"95";
    }
    
    /// 网页加载完成后，，设置字体大小
    NSString *inputNum = [NSString stringWithFormat:@"document.getElementsByTagName('body')[0].style.webkitTextSizeAdjust= '%@'",persent];
    
    /// 网页加载完成后，，设置字体大小
    [webView evaluateJavaScript:inputNum completionHandler:nil];
    
}

#pragma mark - WKNavigationDelegate
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    
    //JS调用OC 方法
    NSURL *URL = navigationAction.request.URL;
    NSString *scheme = [URL scheme];
    if ([scheme isEqualToString:@"native"]) {
        [self.NNN_ModelMethod_yyy YYY_handleCustomAction_yyy:URL];
        decisionHandler(WKNavigationActionPolicyCancel);
        return;
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}



-(YYY_ModelMethod_yyy *)NNN_ModelMethod_yyy{
    if (_NNN_ModelMethod_yyy == nil) {
        _NNN_ModelMethod_yyy = [[YYY_ModelMethod_yyy alloc] init];
        _NNN_ModelMethod_yyy.rootView = self;
        _NNN_ModelMethod_yyy.delegate = self;
    }
    return _NNN_ModelMethod_yyy;
}

- (void)layoutSubviews{
    [super layoutSubviews];
    
    
    [self mas_makeConstraints:^(MASConstraintMaker *make) {
        make.center.mas_equalTo(0);
        make.width.mas_equalTo(self.superview).multipliedBy(0.5);
        make.height.mas_equalTo(self.superview).multipliedBy(0.7);
    }];
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.mas_equalTo(0);
    }];
    
}


@end
